package hrx.controller;

import hrx.entity.Relation;
import hrx.entity.Task;
import hrx.entity.User;
import hrx.service.FileUploadService;
import hrx.service.XsdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/user")
public class XsdController {

    @Autowired
    private XsdService xsdService;

    @Autowired
    private HttpSession session;

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 用户注册
     *
     * @param user
     * @param model
     * @return
     */
    @RequestMapping("/register")
    public String register(User user, Model model) {
        xsdService.save(user);
        return "login";
    }

    /**
     * 登录校检
     *
     * @param user
     * @param model
     * @return
     */
    @RequestMapping("/login")
    public String login(User user, Model model) {
        User dbUser = xsdService.findById(user);
        //判断是否相同
        if (dbUser != null && user.getUser_password().equals(dbUser.getUser_password())) {
            //确实有这个用户
            session.setAttribute("loginUser", dbUser);
            //清空
            model.addAttribute("error", "");
            return "redirect:/index.html";
        } else {
            model.addAttribute("error", "没有这个user");
            return "login";
        }
    }

    /**
     * 发布新任务
     *
     * @param task
     * @return
     */
    @RequestMapping("/userTask")
    public String userTask(Task task) {
        User user = (User) session.getAttribute("loginUser");

        //将用户信息存入新发布的任务中
        task.setPublisher_id(user.getUser_id());
        task.setPublisher_name((user.getUser_name()));

        xsdService.saveTask(task);
        return "redirect:/user/TaskList";
    }

    /**
     * 查询所有任务
     *
     * @return
     */
    @RequestMapping("/TaskList")
    public String TaskList(Model model) {
        List<Task> allTasks = xsdService.findAllTasks();
        model.addAttribute("tasks", allTasks);
        return "userTask";
    }

    /**
     * 删除任务
     *
     * @return
     */
    @RequestMapping("/deleteTask")
    public String deleteTask(Integer id) {
        xsdService.deleteTask(id);
        return "redirect:/user/TaskList";
    }

    /**
     * 查看任务详情
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/findByTask")
    public String findByTask(Integer id, Model model) {
        Task taskById = xsdService.findTaskById(id);
        model.addAttribute("taskById", taskById);
        return "taskInfo";
    }

    /**
     * 接受任务
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/acceptTask")
    public String acceptTask(Integer id, Model model) {
        User user = (User) session.getAttribute("loginUser");
        Integer user_id = user.getUser_id();
        Relation relation = new Relation();
        relation.setTask_id(id);
        relation.setUser_id(user_id);

        //先查找任务信息
        Task task = xsdService.findTaskById(id);
        Integer taskId = task.getId();
        Integer publisherId = task.getPublisher_id();

        //查询任务是否存在，不能重复接取
        Relation byUserIdAndTaskId = xsdService.findByUser_idAndTask_id(relation);

        if (publisherId == user_id) {
            model.addAttribute("errorMessage", "不能接取自己发布的任务");
            return "error";
        } else if (byUserIdAndTaskId != null) {
            model.addAttribute("errorMessage", "已经接取过该任务，不能重复接取");
            return "error";
        } else {
            xsdService.save(relation);
            session.setAttribute("relation", relation);
            model.addAttribute("successMessage", "成功");
            return "success";
        }
    }

    /**
     * 查看接取人的详细信息
     * @param taskId
     * @param model
     * @return
     */
    @RequestMapping("/userInfo")
    public String userInfo(Integer taskId, Model model) {
        Relation relation = xsdService.findByRelation(taskId);
        Integer user_id = relation.getUser_id();

        User byUserId = xsdService.findByUser_id(user_id);

        model.addAttribute("user", byUserId);
        return "userInfo";
    }

    /**
     * 个人信息
     * @param user
     * @param model
     * @return
     */
    @RequestMapping("/userIndex")
    public String userIndex(User user, Model model) {
        return "userIndex";
    }

    /**
     * 资料修改页面
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/userUpdateView")
    public String userUpdateView(Integer id, Model model) {
        User user = (User) session.getAttribute("loginUser");
        model.addAttribute("loginUser", user);
        return "userUpdate";
    }

    /**
     * 资料修改
     *
     * @return
     */
    @RequestMapping("/userUpdate")
    public String userUpdate(User user, Model model) {
        xsdService.save(user);
        return "redirect:/login.html";
    }

    /**
     * 查看接受的任务id
     * @param model
     * @return
     */
    @RequestMapping("/userAtask")
    public String userAtask( Model model) {
        User user = (User) session.getAttribute("loginUser");
        Integer user_id = user.getUser_id();

        List<Relation> relationList = xsdService.findByUser_idRelation(user_id);
        session.setAttribute("relationList", relationList);
        return "redirect:/user/taskList";
    }

    /**
     * 查询用户对应的任务
     * @param model
     * @return
     */
    @RequestMapping("/taskList")
    public String taskList( Model model) {
        List<Relation> relationList = (List<Relation>) session.getAttribute("relationList");

        // 提取所有的 taskId
        List<Integer> taskIds = relationList.stream()
                .map(Relation::getTask_id)  // 假设 Relation 中有 getTaskId() 方法
                .distinct()                // 去重
                .collect(Collectors.toList());

        List<Task> taskList = xsdService.findByIds(taskIds);
        model.addAttribute("taskList", taskList);
        return "userAtask";
    }

    /**
     * 搜索任务
     * @param priceMin 最低价格
     * @param priceMax 最高价格
     * @param words 搜索关键词
     * @param model
     * @return
     */
    @RequestMapping("/search")
    public String search(String school, Integer status , BigDecimal  priceMin, BigDecimal  priceMax, String words, Model model) {

        List<Task> taskList = xsdService.myFind(school,status,priceMin,priceMax,words);
        model.addAttribute("tasks", taskList);
        return "userTask";
    }




















    /**
     * 上传图片
     *
     * @return
     */
    @PostMapping("/uploadP")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file,
                                      HttpServletRequest request) {

        System.out.println("=== 上传请求开始 ===");
        System.out.println("文件名: " + file.getOriginalFilename());
        System.out.println("文件大小: " + file.getSize());

        // 验证文件
        Map<String, Object> validation = fileUploadService.validateFile(file);
        if (!(Boolean) validation.get("success")) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 1);
            errorResult.put("msg", validation.get("message"));
            return errorResult;
        }

        try {
            //保存文件
            String uploadPath = request.getServletContext().getRealPath("/uploads");
            String fileName = fileUploadService.saveFile(file, uploadPath);

            System.out.println("文件保存成功: " + fileName);

            Map<String, Object> successResult = new HashMap<>();
            successResult.put("code", 0);
            successResult.put("msg", "上传成功");

            Map<String, Object> data = new HashMap<>();
            data.put("src", "/uploads/" + fileName);
            data.put("title", file.getOriginalFilename());
            successResult.put("data", data);

            return successResult;

        } catch (IOException e) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 1);
            errorResult.put("msg", "文件保存失败");
            return errorResult;
        }
    }
}


